<?php

namespace app\controllers\group;

use app\common\base\CommonController;

class GroupUserController extends CommonController
{
    /**
     * 加入群组成员
     */
    public function actionAddUser()
    {
        $this->rules = [
            [['groupId', 'add_userId'], 'required'],
            [['groupId', 'add_userId'], 'integer'],
        ];
        $inputs = $this->validate();

        if(!$this->userInfo->isAdmin) {
            return parent::error('ERROR_PERMISSION_DENY', '没有操作权限');
        }

        parent::callModuleService('group', 'GroupUserService', 'addUser', $inputs['groupId'], $inputs['add_userId']);
        $info = parent::callModuleService('group', 'GroupService', 'addUserToJson', $inputs['groupId'], $inputs['add_userId']);
        
        return [
            'success' => $info['success'],
        ];
    }

    /**
     * 删除群组成员
     */
    public function actionDropUser()
    {
        $this->rules = [
            [['groupId', 'drop_userId'], 'required'],
            [['groupId', 'drop_userId'], 'integer'],
        ];
        $inputs = $this->validate();

        if(!$this->userInfo->isAdmin) {
            return parent::error('ERROR_PERMISSION_DENY', '没有操作权限');
        }

        parent::callModuleService('group', 'GroupUserService', 'dropUser', $inputs['groupId'], $inputs['drop_userId']);
        $info = parent::callModuleService('group', 'GroupService', 'dropUserFromJson', $inputs['groupId'], $inputs['drop_userId']);

        return [
            'success' => $info['success'],
        ];
    }

    /**
     * 取得群组中的所有成员
     */
    public function actionListUsers()
    {
        $this->rules = [
            [['groupId'], 'required'],
            [['groupId'], 'integer'],
        ];
        $inputs = $this->validate();
        
        if(!$this->userInfo->isAdmin) {
            return parent::error('ERROR_PERMISSION_DENY', '没有操作权限');
        }

        $info = parent::callModuleService('group', 'GroupService', 'getUsers', $inputs['groupId']);

        $users = [];
        foreach ($info['data'] as $userId) {
            $user = [];
            $username = parent::callModuleService('user', 'AccountService', 'idToUsername', $userId);
            $user['userId'] = $userId;
            $user['username'] = $username;
            array_push($users, $user);
        }

        return [
            'success' => $info['success'],
            'data' => $users,
        ];
    }
}